package edu.dayu.demoDubboClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.*;

public class MyDubboClient {
    private static ExecutorService  executorService = new ThreadPoolExecutor(5,7,3, TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

    private static MyDubboClientHandler clientHandler;

    public Object getBean(final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serviceClass},(proxy, method, args) -> {
            System.out.println("(proxy, method, args) 进入....");
            //{} 部分的代码，客户端每调用一次 hello, 就会进入到该代码
            if (clientHandler == null) {
                initClient();
            }
            //设置要发给服务器端的信息
            //providerName 协议头 args[0] 就是客户端调用 api hello(???), 参数
            clientHandler.setPara(serviceClass.getSimpleName()+"#" +method.getName()+"#"+ args[0]);
            return executorService.submit(clientHandler).get();
        });
    }

    //初始化客户端
    private static void initClient() {
        clientHandler = new MyDubboClientHandler();
//创建 EventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                //向 pipeline 加入解码器
                                pipeline.addLast("decoder", new StringDecoder());
                                //向 pipeline 加入编码器
                                pipeline.addLast("encoder", new StringEncoder());
                                pipeline.addLast(clientHandler);
                            }
                        }
                );
        try {
            bootstrap.connect("127.0.0.1", 6668).sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
